/**
* @description: 周赛308 t3
* @author hewei
* @date 2022/8/28 10:55
* @version 1.0
*/

public class GarbageCollection {

    public int garbageCollection(String[] garbage, int[] travel) {
        int[][] nums = new int[garbage.length][3];
        for (int i = 0; i < garbage.length; i++) {
            String s = garbage[i];
            int a = 0, b = 0, c = 0;
            for (int j = 0; j < s.length(); j++) {
                char x = s.charAt(j);
                if (x == 'M') {
                    ++a;
                } else if (x == 'P') {
                    ++b;
                } else ++c;
            }
            nums[i] = new int[]{a, b, c};
        }
        int a = 0, b = 0, c = 0;
        for (int i = nums.length - 1; i >= 0; i--) {
            if (a == 0 && nums[i][0] != 0) a = i;
            if (b == 0 && nums[i][1] != 0) b = i;
            if (c == 0 && nums[i][2] != 0) c = i;
        }
        int ans = 0;
        for (int i = 0; i < nums.length; i++) {
            if (i <= a) {
                ans += nums[i][0];
                ans += i == 0 ? 0 : travel[i - 1];
            }
            if (i <= b) {
                ans += nums[i][1];
                ans += i == 0 ? 0 : travel[i - 1];
            }
            if (i <= c) {
                ans += nums[i][2];
                ans += i == 0 ? 0 : travel[i - 1];
            }
        }
        return ans;
    }
}
